package com.example.workflow.controller;

import com.example.workflow.dto.OrderStatusCountDto;
import com.example.workflow.dto.OrderTimeSeriesDto;
import com.example.workflow.dto.OrderTypeCountDto;
import com.example.workflow.pojo.Result;
import com.example.workflow.service.AdminStatsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * 管理员工单统计接口
 */
@CrossOrigin
@RestController
@RequestMapping("/admin")
@Slf4j
@PreAuthorize("hasRole('ADMIN')")
public class AdminStatsController {
    
    @Autowired
    private AdminStatsService adminStatsService;
    
    /**
     * 按日期范围统计系统工单总数量，返回时序格式数据
     * 返回格式：{"time":["2023-08-01","2023-08-02",...],"count":[2,3,...]}
     * 
     * @param begin 起始日期，格式：yyyy-MM-dd
     * @param end 结束日期，格式：yyyy-MM-dd
     * @param gap 时间间隔，可选值：day/week/month
     * @return 时序格式的系统工单统计数据
     */
    @GetMapping("/total-count")
    public Result<OrderTimeSeriesDto> getSystemOrderCount(
            @RequestParam(value = "begin") String begin,
            @RequestParam(value = "end") String end,
            @RequestParam(value = "gap") String gap) {
        
        log.info("获取系统整体工单时序计数，begin={}, end={}, gap={}", begin, end, gap);
        
        try {
            LocalDate beginDate = LocalDate.parse(begin);
            LocalDate endDate = LocalDate.parse(end);
            
            // 验证时间间隔参数
            if (!gap.equalsIgnoreCase("day") && !gap.equalsIgnoreCase("week") && !gap.equalsIgnoreCase("month")) {
                return Result.error("时间间隔参数无效，可选值：day/week/month");
            }
            
            // 验证日期范围
            if (beginDate.isAfter(endDate)) {
                return Result.error("起始日期不能晚于结束日期");
            }
            
            OrderTimeSeriesDto stats = adminStatsService.countSystemOrdersByTimeRange(beginDate, endDate, gap);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("日期参数解析错误", e);
            return Result.error("日期参数格式错误，正确格式为：yyyy-MM-dd");
        }
    }
    
    /**
     * 获取系统各状态工单数量统计
     * 返回格式：{"approved":10,"completed":5,"dispatched":3,"draft":2,"pending_l1":1,"pending_l2":0,"processing":8,"rejected":4,"total":33}
     * 
     * @return 各状态工单数量统计
     */
    @GetMapping("/status-count")
    public Result<OrderStatusCountDto> getSystemOrderStatusCount() {
        log.info("获取系统各状态工单数量统计");
        
        try {
            OrderStatusCountDto stats = adminStatsService.countSystemOrdersByStatus();
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取系统工单状态统计出错", e);
            return Result.error("获取工单状态统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取系统各类型工单数量统计
     * 返回格式：{"故障处理":10,"需求申请":5,"日常维护":3,"其它服务":2}
     * 
     * @return 各类型工单数量统计
     */
    @GetMapping("/type-count")
    public Result<OrderTypeCountDto> getSystemOrderTypeCount() {
        log.info("获取系统各类型工单数量统计");
        
        try {
            OrderTypeCountDto stats = adminStatsService.countSystemOrdersByType();
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取系统工单类型统计出错", e);
            return Result.error("获取工单类型统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取工单完成的时间序列统计
     * 返回格式：{"time":["2023-05-21","2023-05-22"],"count":[2,3]}
     * 
     * @param beginDate 开始日期，格式：yyyy-MM-dd
     * @param endDate 结束日期，格式：yyyy-MM-dd
     * @param gap 时间间隔，可选值：day/week/month
     * @return 完成工单的时间序列统计
     */
    @GetMapping("/completed-count")
    public Result<OrderTimeSeriesDto> getCompletedOrderStats(
            @RequestParam("begin") String beginDate, 
            @RequestParam("end") String endDate, 
            @RequestParam("gap") String gap) {
        
        log.info("获取完成工单统计: {} 至 {}, 间隔: {}", beginDate, endDate, gap);
        
        try {
            // 验证参数
            if (!List.of("day", "week", "month").contains(gap)) {
                return Result.error("时间间隔参数无效，必须是day/week/month之一");
            }
            
            OrderTimeSeriesDto data = adminStatsService.getCompletedOrderStats(beginDate, endDate, gap);
            return Result.success(data);
        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("获取完成工单统计失败", e);
            return Result.error("获取统计数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取工单驳回的时间序列统计
     * 返回格式：{"time":["2023-05-21","2023-05-22"],"count":[1,2]}
     * 
     * @param beginDate 开始日期，格式：yyyy-MM-dd
     * @param endDate 结束日期，格式：yyyy-MM-dd
     * @param gap 时间间隔，可选值：day/week/month
     * @return 驳回工单的时间序列统计
     */
    @GetMapping("/rejected-count")
    public Result<OrderTimeSeriesDto> getRejectedOrderStats(
            @RequestParam("begin") String beginDate, 
            @RequestParam("end") String endDate, 
            @RequestParam("gap") String gap) {
        
        log.info("获取驳回工单统计: {} 至 {}, 间隔: {}", beginDate, endDate, gap);
        
        try {
            // 验证参数
            if (!List.of("day", "week", "month").contains(gap)) {
                return Result.error("时间间隔参数无效，必须是day/week/month之一");
            }
            
            OrderTimeSeriesDto data = adminStatsService.getRejectedOrderStats(beginDate, endDate, gap);
            return Result.success(data);
        } catch (IllegalArgumentException e) {
            log.warn("参数错误: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("获取驳回工单统计失败", e);
            return Result.error("获取统计数据失败: " + e.getMessage());
        }
    }
} 